package com.cygsunri.wisdompark.mqtt;


import com.alibaba.fastjson.JSONObject;
import com.cygsunri.wisdompark.callback.entity.AirSensor;
import com.cygsunri.wisdompark.callback.service.ProcessingDataService;
import com.cygsunri.wisdompark.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import java.util.Map;

@Slf4j
@PropertySource(value = "classpath:application.yml")
public class MqttMessageHandler implements MessageHandler {

    @Autowired
    private ProcessingDataService processingDataService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        log.info("------------------------ Start  mqtt----------------------------");
        log.info("message :{}",message.toString());
        String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
        String msg = message.getPayload().toString();
        log.info("topic:{},msg:{}",topic,msg);
        //空气传感器
        if(topic.contains("/zkyc/device/in/")){
            if(StringUtils.isNotEmpty(msg)){
                AirSensor airSensor = JSONObject.parseObject(msg, AirSensor.class);
                Map map= airSensor.getData();
                map.put("time", DateUtil.nowMilliSeconds());
                try {
                    processingDataService.saveData(airSensor.getDevCode(), airSensor.getData(),"mqtt");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }else{

        }
        log.info("------------------------ end  mqtt----------------------------");
    }

}
